<template>
  <div class="order-management">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
            <el-option label="待付款" value="0" />
            <el-option label="待发货" value="1" />
            <el-option label="已发货" value="2" />
            <el-option label="已完成" value="3" />
            <el-option label="已取消" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 按钮区域 -->
    <el-card class="button-card">
      <el-button type="primary" @click="handleExport">导出订单</el-button>
      <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
        批量删除
      </el-button>
      <el-button type="success" @click="createTestOrder">创建测试订单(待付款)</el-button>
    </el-card>

    <!-- 展示区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="orderList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单编号" prop="orderNo" width="180" />
        <el-table-column label="订单金额" prop="amount" width="120">
          <template #default="{ row }">
            ¥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" prop="status" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="收货人" prop="receiverName" width="120" />
        <el-table-column label="联系电话" prop="receiverPhone" width="120" />
        <el-table-column label="收货地址" prop="receiverAddress" show-overflow-tooltip />
        <el-table-column label="下单时间" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" width="250">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            <!-- 显示状态值，帮助调试 -->
            <span style="margin: 0 5px; font-size: 12px; color: #999;">[{{row.status}}]</span>
            <!-- 尝试使用字符串比较 -->
            <el-button 
              v-if="row.status === '0' || row.status === 'PENDING'"
              type="warning" 
              link 
              @click="handleCancel(row)"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @update:current-page="handleCurrentChange"
          @update:page-size="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="dialogVisible"
      width="800px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ currentOrder.amount?.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ currentOrder.createTime }}</el-descriptions-item>
        <el-descriptions-item label="收货人">{{ currentOrder.receiverName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.receiverPhone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.receiverAddress }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="currentOrder.items" style="margin-top: 20px">
        <el-table-column label="商品名称" prop="productName" />
        <el-table-column label="单价" prop="price" width="120">
          <template #default="{ row }">
            ¥{{ row.price?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="quantity" width="100" />
        <el-table-column label="小计" width="120">
          <template #default="{ row }">
            ¥{{ (row.price * row.quantity)?.toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listOrders, getOrder, deleteOrder, cancelOrder, createTestOrder as createTestOrderApi } from '@/api/orders'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderNo: '',
  status: '',
  createTime: []
})

// 数据列表
const orderList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedIds = ref([])

// 订单详情
const dialogVisible = ref(false)
const currentOrder = ref({})

// 获取订单列表
const getList = async () => {
  loading.value = true
  try {
    console.log('==== 开始获取订单列表 ====')
    console.log('查询参数:', queryParams)
    
    const res = await listOrders(queryParams)
    console.log('订单API响应:', res)
    
    orderList.value = res.data.list
    total.value = res.data.total
    
    // 调试：打印订单列表和状态
    console.log('订单列表数据 (共' + orderList.value.length + '条):', orderList.value)
    
    // 遍历所有订单，检查状态
    orderList.value.forEach((order, index) => {
      console.log(`订单[${index}] ID:${order.id || order.orderId}, 状态:${order.status}, 类型:${typeof order.status}`)
    })
    
    console.log('==== 订单列表获取完成 ====')
  } catch (error) {
    console.error('获取订单列表失败:', error)
  }
  loading.value = false
}

// 查询按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.orderNo = ''
  queryParams.status = ''
  queryParams.createTime = []
  handleQuery()
}

// 选择条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    '0': 'warning',
    '1': 'primary',
    '2': 'success',
    '3': 'info',
    '4': 'danger'
  }
  return statusMap[status] || 'info'
}

// 判断订单是否可以取消
const isOrderCancellable = (order) => {
  if (!order) return false
  
  console.log('判断订单是否可取消:', order)
  
  // 打印订单状态
  console.log('订单状态:', order.status, '类型:', typeof order.status)
  
  // 检查各种可能的待付款状态表示
  const status = order.status
  const isPending = 
    status === '0' || 
    status === 0 || 
    status === 'PENDING' || 
    status === 'pending' || 
    status === '待付款' ||
    (typeof status === 'string' && status.toLowerCase() === 'pending')
  
  console.log('是否可取消:', isPending)
  return isPending
}

// 获取状态文本
const getStatusText = (status) => {
  console.log('获取状态文本，原始状态值:', status, '类型:', typeof status)
  
  // 尝试将数字字符串转换为数字
  let statusValue = status
  if (typeof status === 'string' && !isNaN(status)) {
    statusValue = parseInt(status)
  }
  
  const statusMap = {
    '0': '待付款',
    0: '待付款',
    '1': '待发货',
    1: '待发货',
    '2': '已发货',
    2: '已发货',
    '3': '已完成',
    3: '已完成',
    '4': '已取消',
    4: '已取消',
    'PENDING': '待付款',
    'PAID': '已付款',
    'SHIPPED': '已发货',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  
  const result = statusMap[statusValue] || '未知'
  console.log('状态文本结果:', result)
  return result
}

// 查看订单详情
const handleDetail = async (row) => {
  try {
    const res = await getOrder(row.id)
    currentOrder.value = res.data
    dialogVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败:', error)
  }
}

// 取消订单
const handleCancel = (row) => {
  console.log('==== 准备取消订单 ====')
  console.log('订单数据:', row)
  
  ElMessageBox.confirm('确认要取消该订单吗？取消后不可恢复', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      console.log('用户确认取消订单')
      
      // 确保使用正确的ID字段
      const orderId = row.id || row.orderId;
      console.log('取消订单ID:', orderId);
      
      console.log('发送取消请求...')
      const response = await cancelOrder(orderId);
      console.log('取消订单响应:', response);
      
      ElMessage.success('订单已取消');
      getList();
    } catch (error) {
      console.error('取消订单失败:', error);
      console.error('错误详情:', error.response || error.message || error);
      ElMessage.error('取消订单失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    }
  }).catch(() => {
    console.log('用户取消操作')
  });
}

// 导出订单
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 创建测试订单
const createTestOrder = async () => {
  try {
    ElMessage.info('正在创建测试订单...')
    const response = await createTestOrderApi()
    console.log('创建测试订单响应:', response)
    ElMessage.success('测试订单创建成功')
    getList() // 刷新订单列表
  } catch (error) {
    console.error('创建测试订单失败:', error)
    ElMessage.error('创建测试订单失败: ' + (error.response?.data?.message || error.message || '未知错误'))
  }
}

// 页面加载时执行
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.order-management {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .button-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 